<template>
  <div class="app-container">

    <el-table v-loading="loading" :data="shoppingCartListList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center"/>
      <el-table-column label="商品编号" align="center" prop="skuId"/>
      <el-table-column label="商品数量" align="center" prop="skuNum"/>
      <el-table-column label="商品单价" align="center" prop="inputPrice"/>
      <el-table-column label="商品总价" align="center" prop="skuTotalPrice"/>
      <el-table-column label="购物车状态" align="center" prop="cartStatus"/>
      <el-table-column label="商品名称" align="center" prop="skuName"/>
      <el-table-column label="商品状态" align="center" prop="saleStatus"/>
      <el-table-column label="商品图片" align="center" prop="imgUrl" width="100">
        <template slot-scope="scope">
          <image-preview :src="scope.row.skuImg" :width="50" :height="50"/>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"
                     v-hasPermi="['shopping:shoppingCartList:remove']">删除
          </el-button>
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)"
                     v-hasPermi="['shopping:shoppingCartList:edit']">移入关注列表
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <div class="total-price">
      <span>合计金额: {{ totalPrice }}</span>
      <el-button type="primary" @click="commtent" v-if="num===0" disabled>点击下单</el-button>
      <el-button type="primary" @click="handlePlaceOrder" v-if="num===1">点击下单</el-button>
    </div>

    <el-dialog title="结算页面" :visible.sync="dialogFormVisible" width="80%">

      <!--      回显不管-->
      <el-table :data="cartList" width="80%">
        <el-table-column property="skuNum" label="商品数量" width="210"></el-table-column>
        <el-table-column property="inputPrice" label="商品单价" width="210"></el-table-column>
        <el-table-column property="skuTotalPrice" label="商品总价" width="300"></el-table-column>
        <el-table-column property="skuName" label="商品名称" width="300"></el-table-column>
        <el-table-column label="商品图片" align="center" prop="imgUrl" width="300">
          <template slot-scope="scope">
            <image-preview :src="scope.row.skuImg" :width="50" :height="50"/>
          </template>
        </el-table-column>
      </el-table>

      <template>
        <div class="form-container">
          <el-form :model="orderDetails" label-width="100px">
            <el-form-item label="订单编号">
              <el-input v-model="orderCode"></el-input>
            </el-form-item>
            <el-form-item label="订单金额">
              <el-input v-model="orderDetails.orderPrice"></el-input>
            </el-form-item>
            <el-form-item label="实际金额">
              <el-input v-model="orderDetails.paidAmount"></el-input>
            </el-form-item>
            <el-form-item label="是否用优惠券">
              <el-switch v-model="delivery"  @change="isSelectCoupon()"></el-switch>
            </el-form-item>
            <el-form-item label="优惠券" v-if="delivery">
              <el-select v-model="coupon" value-key="couponId" placeholder="请选择活动区域"
                         @change="selectCoupon(coupon)">
                <el-option v-for="item in couponList" :key="item.couponId" :value="item"
                           :label="item.couponName"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="用户地址选择">
              <el-select v-model="taskItem" value-key="0" placeholder="请选择用户区域" @change="taskUpd(taskItem)"
                         default-first-option>
                <el-option label="无选择" key="0" value="0"></el-option>
                <el-option v-for="item in taskList" :key="item.takeId"
                           :label="'地址:'+item.takeAddress+',用户名:'+item.takeName+',手机号:'+item.takePhone"
                           :value="item"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="收货人">
              <el-input v-model="orderDetails.takeName"></el-input>
            </el-form-item>
            <el-form-item label="收货地址">
              <el-input v-model="orderDetails.takeAddress"></el-input>
            </el-form-item>
            <el-form-item label="收货电话">
              <el-input v-model="orderDetails.takePhone"></el-input>
            </el-form-item>
          </el-form>
        </div>
      </template>
      <div slot="footer" class="dialog-footer">
        <el-button @click="Checkout(2)">等会结账</el-button>
        <el-button type="primary" @click="Checkout(1)">现在结账</el-button>
      </div>

    </el-dialog>



  </div>
</template>

<script>
import {
  addCartOrder,
  listShoppingCartList,
  orderGetDetailInstall,
  submitGetUUID
} from "@/api/shopping/shoppingCartList";
import {getInfo} from "@/api/login";
import {getOrderResponse, getUserTakeList, pay} from '@/api/order/order'
import {computeCoupon, getUserCouponList} from "@/api/marketing/coupon";

export default {
  name: "ShoppingCartList",
  data() {
    return {
      uuid:null,
      orderForm: {
        userId: null,
        uuid: "",
        list: [
          {
            skuId: undefined,
            sumPrice: undefined,
            skuNumber: undefined
          }
        ]
      },
      taskList: [],
      taskItem: {},
      orderCode: null,
      delivery: false,
      orderDetails: {
        orderId: null,//订单id
        couponId: null,//优惠券id
        orderPrice: null,//订单金额
        paidAmount: null,//实际金额
        payType: "支付宝",//默认支付宝
        confirmReceiptTime: null,//收货人
        takeName: null,//收货地址
        takeAddress: null,//收货人电话
        takePhone: null
      },
      zhifubao: {
        paidAmount: '',     //实际金额
        skuName: '',     //sku名: null
        orderCode: ''
      },
      //优惠卷下拉款选中的对象
      coupon: {},
      //优惠卷动态下拉框
      couponList: [],
      //策略接口的参数对象
      computeReq: {
        couponTypeId: null,   //优惠卷类型
        discountAmount: null,   //满减金额
        discountPerentage: null,  //折扣百分比
        minOrderAmount: null,   //所需最低金额
        orderPrice: null  //原价格
      },
      cartList: [],
      dialogFormVisible: false,

      formLabelWidth: '120px',

      totalPrice: 0,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 购物车列表表格数据
      shoppingCartListList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      userId: 0,
      //下单
      // 表单参数
      form: {},
      // 表单校验
      rules: {},
      num: 0,
      timer: null,


    };
  },
  created() {
    this.getUserInfo();
    this.getUUID();
  },
  methods: {
    //是否选择优惠卷
    isSelectCoupon(){
      if(this.delivery===false){
        this.orderDetails.paidAmount=this.orderDetails.orderPrice;
      }
    },
    getUUID(){
      submitGetUUID().then(res => {
        this.uuid = res.data;
      })
    },
    Checkout(Type) {
      if (Type == 1) {
        pay(this.orderCode)
        {
          this.zhifubao.paidAmount=this.orderDetails.paidAmount;
          window.open('http://localhost:9205/alipay/pay?&subject=' + this.zhifubao.skuName + '&traceNo=' + this.orderCode + '&totalAmount=' + this.zhifubao.paidAmount)
        }
        orderGetDetailInstall(this.orderDetails).then(res => {
          if (res.data.code == 200) {
            this.$message.success("下单成功")
            this.dialogFormVisible = false
            this.getList()
            this.orderNull()
          } else {
            this.$message.error("下单失败");
            this.dialogFormVisible = false
          }
        })

      } else {
        window.location.reload();
      }

    },

    //清空信息单
    orderNull() {
      this.orderDetails = {
        orderId: null,    //订单id
        couponId: null,     //优惠券id
        orderPrice: null,     //订单金额
        paidAmount: null,     //实际金额
        payType: "支付宝",    //默认支付宝
        confirmReceiptTime: null,     //收货人
        takeName: null,    //收货地址
        takeAddress: null,//收货人电话
        takePhone: null
      }
    },

    taskUpd(taskItem) {

      this.orderDetails.takeName = taskItem.takeName
      this.orderDetails.takeAddress = taskItem.takeAddress
      this.orderDetails.takePhone = taskItem.takePhone
      console.log(taskItem)

    },
    getTakeList() {
      getUserTakeList(this.userId).then(res => {
        this.taskList = res.data
      })
    },
    commtent() {
      this.$message.error("请添加要购买的物品")
    },
    getUserInfo() {
      getInfo().then(res => {
        this.userId = res.data.user.userId;
        console.log(this.userId)
        this.orderForm.userId = this.userId
        this.getList();
      })
    },
    /** 查询购物车列表列表 */
    getList() {
      this.loading = true;
      listShoppingCartList(this.userId).then(response => {
        this.shoppingCartListList = [];
        for (const item of response.data) {
          if (item.cartStatus !== 2) {
            this.shoppingCartListList.push(item);
          }
        }
        this.loading = false;
      });
    },

    // 表单重置
    reset() {
      this.form = {
        middenId: null,
        cartId: null,
        skuId: null,
        skuNum: null,
        inputPrice: null,
        skuTotalPrice: null,
        cartStatus: null,
        fountTime: null,
        updateTime: null
      };
      this.resetForm("form");
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.orderForm.list = []; // 清空orderForm.list
      this.totalPrice = 0;
      this.cartList = [];
      this.num = 0;
      this.orderDetails.orderPrice = 0
      for (const item of selection) {
        this.num = item != null ? 1 : 0;
        this.totalPrice += item.skuTotalPrice;
        this.orderDetails.orderPrice += item.skuTotalPrice;
        this.zhifubao.skuName += "," + item.skuName;
        // 将每个选中的商品添加到cartList中
        this.cartList.push(item);
        // 为orderForm.list添加空对象
        this.orderForm.list.push({skuId: item.skuId, sumPrice: item.skuTotalPrice, skuNumber: item.skuNum});
      }
      // 遍历selection数组，为orderForm.list中的每个元素赋值
      this.orderDetails.paidAmount = this.orderDetails.orderPrice
      this.zhifubao.paidAmount = this.orderDetails.orderPrice
      this.zhifubao.skuName = this.zhifubao.skuName.substring(1)
      // console.log(this.zhifubao.skuName)
      // console.log(this.orderDetails.orderPrice);
      // console.log(this.orderForm.list);
      // console.log(this.num);
      // console.log(this.totalPrice);
      // console.log(this.cartList);
    },


    //下单操作
    handlePlaceOrder() {
      this.orderForm.uuid=this.uuid;
      //调用请求方法
      addCartOrder(this.orderForm).then(res => {
        if (res.code == 500) {
          this.$message.error(res.msg);
        } else {
          this.$message.success("下单成功");
          this.startTimer();//成功后调用轮询
        }
      })
    },
    /**获取下单后的redis内存数据**/
    getAddCartOrderResponse() {
      this.orderForm.uuid=this.orderForm.uuid+"RESPONSE";
      getOrderResponse(this.orderForm.uuid).then(res => {
        if (res.code == 200) {
          this.stop();
          this.getTakeList();
          this.orderDetails.orderId = res.data.orderId
          this.orderCode = res.data.orderCode
          this.getCouponList();
          this.dialogFormVisible = true;
          this.$message.success("请填写订单详情");
        } else {
          this.$message.error("正在获取订单详情，请稍等")
        }
      })
    },
    //轮询方法
    startTimer() {
      if (this.timer) {
        clearInterval(this.timer);
      }
      this.timer = window.setInterval(() => {
        setTimeout(this.getAddCartOrderResponse, 0);
      }, 1000)
    },
    //轮询结束
    stop() {
      clearInterval(this.timer);
      this.timer = null;
    },


    /** 删除按钮操作 */
    handleDelete(row) {

    },

    /** 获取用户所有的优惠卷*/
    getCouponList() {
      getUserCouponList(this.userId).then(res => {
        this.couponList = res.data;
      })
    },
    /** 用户选择用户卷结算 */
    selectCoupon(coupon) {
      // 策略接口调用
      console.log(coupon);
      this.computeReq.minOrderAmount = coupon.minOrderAmount;
      this.computeReq.couponTypeId = coupon.couponTypeId;
      this.computeReq.orderPrice = this.orderDetails.orderPrice;
      this.computeReq.discountPerentage = coupon.discountPerentage;
      this.computeReq.discountAmount = coupon.discountAmount;
      computeCoupon(this.computeReq).then(res => {
        if (res.code == 200) {
          this.$message.success(res.msg);
          this.orderDetails.paidAmount = res.data;
          this.zhifubao.paidAmount = this.orderDetails.paidAmount
        }
      })

    }
  }
};
</script>
<style>
.total-price {
  background-color: #f0f0f0; /* 设置背景颜色 */
  padding: 10px; /* 设置内边距 */
  width: 100%; /* 设置宽度 */
  height: 50px; /* 设置高度 */
  display: flex; /* 使用flex布局 */
  justify-content: space-between; /* 元素间距平均分布 */
  align-items: center; /* 垂直居中 */
}

.total-price span {
  font-size: 18px; /* 设置字体大小 */
  color: #333; /* 设置文字颜色 */
}

.form-container {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100vh; /* 设置合适的高度 */
}
</style>
